﻿<template>
  <a-drawer :title="title" :visible="visible" width="90%" @close="() => {
    this.visible = false
  }
    ">
    <a-form-model ref="form" :model="entity" :rules="rules" v-bind="layout">
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="客户名称" prop="CustomerName">
            <CustRemoteSearchByCondition v-model="entity.CustomerId" :disabled="disabled" :is-my-data="false"
              mode="default" placeholder="检索客户(名称/编号)(省市区名称禁止查询)" @BindCustomer="BindCustomer">
            </CustRemoteSearchByCondition>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="客户经理" prop="AccountManager">
            <a-input v-model="entity.AccountManager" autocomplete="off" disabled placeholder="客户经理" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="申请编号" prop="DocumentNo">
            <a-input v-model="entity.DocumentNo" autocomplete="off" disabled placeholder="系统自动生成" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="经办人" prop="Transactor">
            <a-select v-model="entity.Transactor" :disabled="disabled" placeholder="请选择">
              <a-select-option v-for="item in List" :key="item.Id" :value="item.Id">
                {{ item.RealName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="紧急程度" prop="Urgency">
            <a-select v-model="entity.Urgency" :disabled="disabled" placeholder="紧急程度" style="width: 100%">
              <a-select-option v-for="item in List2" :key="item.Id" :value="item.DicName">
                {{ item.DicName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="样品用途" prop="purposes">
            <a-select v-model="entity.Purpose" :disabled="disabled" placeholder="样品用途" style="width: 100%">
              <a-select-option v-for="item in List3" :key="item.Id" :value="item.DicName">
                {{ item.DicName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="收件人" prop="Addressee">
            <CustomerAddress v-model="entity.Addressee" :UserId="entity.CustomerId" :disabled="disabled"
              placeholder="选择收件人" @onAddress="onAddress" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="收件电话" prop="AddresseeTel">
            <a-input v-model="entity.AddresseeTel" autocomplete="off" disabled placeholder="收件电话" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="收货地址" prop="ReceiveAddress">
            <!-- <CustomerAddress v-model="entity.ReceiveAddress" :UserId="entity.CustomerCode" :disabled="disabled" /> -->
            <a-textarea v-model="entity.ReceiveAddress" autocomplete="off" disabled />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="申请日期">
            <a-date-picker v-model="entity.ApplyDate" :disabled="disabled" format="YYYY-MM-DD" style="width: 100%" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="备注" prop="Remark">
            <a-textarea v-model="entity.Remark" :disabled="disabled" autocomplete="off" />
          </a-form-model-item>
        </a-col>
        <a-col v-if="disabled" :span="8">
          <a-form-model-item v-if="entity.SampleStatus" label="试用说明">
            <a-textarea v-model="entity.SampleTrialRemark" autocomplete="off" disabled placeholder="试用说明" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col v-if="disabled" :span="8">
          <a-form-model-item v-if="entity.ApprovalStatus" label="审核日期">
            <a-date-picker v-model="entity.ApprovalDate" disabled format="YYYY-MM-DD" style="width: 100%" />
          </a-form-model-item>
        </a-col>
        <a-col v-if="disabled" :span="8">
          <a-form-model-item v-if="entity.ApprovalStatus" label="审批意见" prop="ApprovalComments">
            <a-textarea v-model="entity.ApprovalComments" autocomplete="off" disabled />
          </a-form-model-item>
        </a-col>
        <a-col v-if="disabled" :span="8">
          <a-form-model-item v-if="entity.DeliverStatus == 2" label="快递单号">
            <a-input v-model="entity.TrackingNumber" autocomplete="off" disabled placeholder="快递单号" />
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <a-tabs :active-key="activeKey" @change="tabChange">
      <a-tab-pane key="1" tab="样品明细">
        <div style="text-align: right">
          <a-button v-if="title != '审核' && title != '查看'" type="primary" @click="addTable">添加</a-button>&nbsp;
        </div>
        <a-table ref="table" :bordered="true" :columns="columns" :dataSource="data" :pagination="false"
          :rowKey="(row, index) => row.Id || index" :scroll="{ y: 460 }" class="tables" size="small"
          @change="handleTableChange">
          <template slot="cInvName" slot-scope="text, record">
            <span>{{ record.ProductId }}/{{ record.cInvName }}</span>
          </template>
          <span slot="action" slot-scope="text, record, index">
            <template>
              <a v-if="hasPerm('Quot_PriceListDetails.Delete')" :disabled="disabled"
                @click="handleDelete([record.Id], index)">删除</a>
            </template>
          </span>
          <!-- 主数量 -->
          <template slot="MainQuantity" slot-scope="text, record">
            <a-input v-model="record.MainQuantity" :disabled="disabled" class="input" size="small"
              style="text-align: right" type="number"></a-input>
          </template>
          <!-- 批次 -->
          <template slot="Batch" slot-scope="text, record">
            <a-input v-model="record.Batch" class="input" size="small" type="number"></a-input>
          </template>
          <!-- 备注 -->
          <template slot="Remark" slot-scope="text, record">
            <a-input v-model="record.Remark" :disabled="disabled" class="input" size="small"></a-input>
          </template>
        </a-table>
        <div style="height: 50px;"></div>
      </a-tab-pane>
      <a-tab-pane v-if="AttachShow" key="2" tab="附件列表">
        <a-table ref="tableAttach" :bordered="true" :columns="columnsAttach" :dataSource="dataAttach" :loading="loading"
          :pagination="paginationAttach" :rowKey="(row, index) => row.Id" :scroll="{ y: 530 }" size="small"
          @change="handleAttachmentsTableChange">
          <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime, 'YYYY-MM-DD HH:mm') }}</span>
          <span slot="action" slot-scope="text, record">
            <template>
              <a :href="record.FileURL">下载</a>
              <a-divider v-if="hasPerm('Base_AttachmentsList.Delete')" type="vertical" />
              <a v-if="hasPerm('Base_AttachmentsList.Delete')" @click="handleDeleteAttach([record.Id])">删除</a>
            </template>
          </span>
        </a-table>
      </a-tab-pane>
    </a-tabs>
    <MaterialChoose ref="materialChoose" @onChoose="handleChoose"></MaterialChoose>
    <CustomerLinkMan ref="LinkMan" :row="{ Id: entity.CustomerId, cCusName: entity.CustomerName }" @pushLink="pushLink" />
    <div :style="{
      position: 'absolute',
      right: 0,
      bottom: 0,
      width: '100%',
      borderTop: '1px solid #e9e9e9',
      padding: '10px 16px',
      background: '#fff',
      textAlign: 'right',
      zIndex: 1
    }">
      <!-- <a-button type="primary" v-if="title != '审核' && title != '查看'" @click="addTable">添加</a-button>&nbsp; -->
      <a-button @click="close">取消</a-button>&nbsp;
      <a-button v-if="title != '审核' && title != '查看'" type="primary" @click="handleSubmit">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import CustomerLinkMan from '@/views/CustomerManagement/Cust_CustomerLinkMan/EditForm.vue'
import CustomerAddress from '@/components/CustomerAddress/ListCopy.vue'
import OperatorCache from '@/utils/cache/OperatorCache'
import MaterialChoose from '@/components/MaterialChoose/MaterialChooseCopy1.vue'
import CustRemoteSearchByCondition from '@/components/RemoteSearch/CustRemoteSearchByCondition'
import moment from 'moment'

const columns = [
  { title: '品名', dataIndex: 'cInvName', scopedSlots: { customRender: 'cInvName' }, width: '20%' },
  { title: '规格型号', dataIndex: 'cInvStd' },
  { title: '数量', dataIndex: 'MainQuantity', scopedSlots: { customRender: 'MainQuantity' } },
  { title: '计量单位(克)', dataIndex: 'unit', scopedSlots: { customRender: 'unit' } },
  // { title: '批次', dataIndex: 'Batch', scopedSlots: { customRender: 'Batch' } },
  { title: '备注', dataIndex: 'Remark', scopedSlots: { customRender: 'Remark' } },
  { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' } }
]

const columnsAttach = [
  { title: '上传时间', dataIndex: 'CreateTime', width: '10%', align: 'center', scopedSlots: { customRender: 'CreateTime' } },
  { title: '文件地址', dataIndex: 'FileURL', align: 'center' },
  { title: '操作', dataIndex: 'action', align: 'left', width: '10%', scopedSlots: { customRender: 'action' } }
]
export default {
  props: {
    parentObj: Object,
    disabled: { type: Boolean, required: false }
  },
  components: {
    CustRemoteSearchByCondition,
    MaterialChoose,
    OperatorCache,
    CustomerAddress,
    CustomerLinkMan
  },
  data() {
    return {
      columns,
      columnsAttach,
      data: [],
      dataAttach: [],
      selectedRowKeys: [],
      CustomerDisabled: null,
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      Id: '',
      a: 1,
      activeKey: '1',
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true,
        onShowSizeChange: (current, pageSize) => {
          this.pageSize = pageSize
        }
      },
      paginationAttach: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true,
        onShowSizeChange: (current, pageSize) => {
          this.pageSize = pageSize
        }
      },
      List: [],
      filters: {},
      DepartmentIdTreeData: [],
      sorter: { field: 'Id', order: 'desc' },
      visible: false,
      AttachShow: false,
      List1: [],
      List2: [],
      List3: [],
      linkList: [],
      loading: false,
      entity: {},
      rules: {
        CustomerName: [{ required: true, message: '未输入', trigger: 'change' }],
        // Department: [{ required: true, message: '未输入', trigger: 'change' }],
        AccountManager: [{ required: true, message: '未输入', trigger: 'blur' }],
        Transactor: [{ required: true, message: '未输入', trigger: 'blur' }],
        DeliverAddress: [{ required: true, message: '未输入', trigger: 'blur' }],
        Addressee: [{ required: true, message: '请选择', trigger: 'change' }],
        AddresseeTel: [{ required: true, message: '未输入', trigger: 'blur' }],
        ReceiveAddress: [{ required: true, message: '未输入', trigger: 'blur' }]
      },
      title: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    onAddress(row) {
      this.$set(this.entity, 'Addressee', row.Addressee)
      this.$set(this.entity, 'AddresseeTel', row.TelNumber)
      this.$set(this.entity, 'ReceiveAddress', row.Address)
    },
    changeAddressee(e) {
      console.log(e)
      const arr = this.linkList.filter(item => item.Id == e)
      console.log(arr)
      if (arr.length > 0) {
        this.$set(this.entity, 'Addressee', arr[0].Name)
        this.$set(this.entity, 'AddresseeTel', arr[0].Tel_Code)
        this.$set(this.entity, 'ReceiveAddress', arr[0].Address)
      }
    },
    pushLink(obj) {
      this.linkList.push(obj)
    },
    // 添加收件人
    addLink() {
      this.$refs.LinkMan.openForm(null, '新建客户联系人信息', '申请')
    },
    // 联系人
    contactPerson(id) {
      this.$http
        .post('/CustomerManagement/Cust_CustomerLinkMan/GetDataListByConditions', {
          Search: [
            {
              Condition: 'CustomerId',
              Keyword: id
            }
          ],
          ...this.filters
        })
        .then(resJson => {
          this.loading = false
          this.linkList = resJson.Data
        })
    },
    getSelect() {
      this.$http
        .post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', {
          Condition: 'DicKey',
          Keyword: 'SampleUse'
        })
        .then(res => {
          if (res.Success) {
            this.List1 = res.Data.DictionaryDetailsList
          }
        })
      this.$http
        .post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', {
          Condition: 'DicKey',
          Keyword: 'EmergencyDegree'
        })
        .then(res => {
          if (res.Success) {
            this.List2 = res.Data.DictionaryDetailsList
          }
        })
      this.$http
        .post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', {
          Condition: 'DicKey',
          Keyword: 'SampleUse'
        })
        .then(res => {
          if (res.Success) {
            this.List3 = res.Data.DictionaryDetailsList
          }
        })
    },
    BindCustomer(val) {
      this.$set(this.entity, 'CustomerId', val == null ? null : val.Id)
      this.$set(this.entity, 'CustomerName', val == null ? null : val.cCusName)
      this.$set(this.entity, 'AccountManager', val == null ? null : val.PrincipalName)
      // 清空
      this.$set(this.entity, 'Addressee', '')
      this.$set(this.entity, 'AddresseeTel', '')
      this.$set(this.entity, 'ReceiveAddress', '')
      this.contactPerson(val == null ? null : val.Id)
    },
    op() {
      return OperatorCache.info
    },
    tabChange(key) {
      this.activeKey = key
      if (key == '2') {
        this.getDataListAttach()
      }
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    handleDelete(ids, index) {
      if (ids[0]) {
        var thisObj = this
        // this.$confirm({
        //   title: '确认删除吗?',
        //   onOk () {
        //     return new Promise((resolve, reject) => {
        //       thisObj.$http.post('/SampleManagement/SPL_SampleApplyDetails/DeleteData', ids).then(resJson => {
        //         resolve()

        //         if (resJson.Success) {
        //           thisObj.$message.success('操作成功!')

        //           thisObj.getDataList()
        //         } else {
        //           thisObj.$message.error(resJson.Msg)
        //         }
        //       })
        //     })
        //   }
        // })
        this.$confirm('确认删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          thisObj.$http
            .post('/SampleManagement/SPL_SampleApplyDetails/DeleteData', ids)
            .then(resJson => {
              // resolve()

              if (resJson.Success) {
                thisObj.$message.success('操作成功!')

                thisObj.getDataList()
              } else {
                thisObj.$message.error(resJson.Msg)
              }
            })
        })
      } else {
        this.data.splice(index, 1)
      }
    },
    getUserList() {
      this.selectedRowKeys = []
      this.loading = true
      this.$http.post('/Base_Manage/Base_User/GetDataList', {}).then(resJson => {
        this.loading = false
        this.List = resJson.Data
      })
    },
    // 反填
    getDataList() {
      this.$http
        .post('/SampleManagement/SPL_SampleApplyMain/GetTheDataOfAll', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: 'Id',
          SortType: 'desc',
          Search: {
            Condition: 'Id',
            Keyword: this.Id
          }
        })
        .then(res => {
          if (res.Success) {
            this.entity = res.Data
            if (this.entity['ApplyDate']) {
              this.entity['ApplyDate'] = moment(this.entity['ApplyDate'])
            }
            if (this.entity['ApprovalDate']) {
              this.entity['ApprovalDate'] = moment(this.entity['ApprovalDate'])
            }
            if (this.entity.DeliverStatus == 2) {
              this.AttachShow = true
            }
            this.data = res.Data.SSAD_List
            this.data.forEach(item => {
              item.cInvCode = item.ProductId
            })
            this.contactPerson(this.entity.CustomerId)
          } else {
            this.$message.error(res.Msg)
          }
        })
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }

      this.getDataList()
    },
    addTable() {
      if (!this.entity.CustomerName) {
        this.$message.warning('请先选择客户')
      } else {
        this.$refs.materialChoose.openChoose(null, this.data)
      }
    },
    init() {
      this.visible = true
      this.$http.post('/Base_Manage/Base_Department/GetTreeDataList', {}).then(resJson => {
        if (resJson.Success) {
          this.DepartmentIdTreeData = resJson.Data
        }
      })
      this.data = []
      this.entity = {}
      this.entity = { Id: '', Status: 0, CreateTime: moment(), ExpectedDate: moment() }
      this.entity.ApplyDate = moment(new Date())
      this.entity.ApprovalDate = moment(new Date())
      this.$set(this.entity, 'Transactor', this.op().Id)
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    openForm(id, title, item) {
      this.init()
      this.title = title
      this.getSelect()
      if (item) {
        this.CustomerDisabled = item.cCusName
        this.$set(this.entity, 'CustomerName', item.cCusName)
        this.$set(this.entity, 'CustomerId', item.Id || item.cCusCode)
      }
      if (id) {
        this.loading = true
        this.Id = id
        this.a = 2
        this.getDataList()
      }
    },
    close() {
      this.visible = false

      this.entity = {}
    },
    handleChoose(a) {
      var ar = []
      this.data.forEach(item => {
        a.forEach((val, i) => {
          if (item.ProductId == val.cInvCode) {
            ar.push(val)
            delete a[i]
          }
        })
      })
      if (ar.length == 0) {
        a.forEach(item => {
          this.data.push({
            ProductId: item.cInvCode,
            cInvName: item.cInvName,
            cInvCode: item.cInvCode,
            cInvStd: item.cInvStd
          })
        })
      } else {
        this.$message.error('重复产品已筛选掉')
        a.forEach(item => {
          this.data = [...this.data, item]
        })
      }
    },
    handleSubmit() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        this.loading = true
        if (this.title == '修改') this.entity.ApprovalStatus = null
        if (this.data.length == 0) {
          this.$message.warning('请添加样品')
          return
        }
        const num = this.data.some(item => {
          return !item.MainQuantity || item.MainQuantity == 0
        })
        if (num) {
          this.$message.warning('填写数量')
          return
        }
        const entityData = { ...this.entity }
        this.SSAD_List = [...this.data]
        entityData.SSAD_List = this.SSAD_List
        this.$http.post('/SampleManagement/SPL_SampleApplyMain/SaveData', entityData).then(resJson => {
          this.loading = false
          if (resJson.Success) {
            this.$message.success('操作成功!')
            this.visible = false
            this.parentObj.getDataList()
          } else {
            this.$message.error(resJson.Msg)
          }
        })
      })
    },
    // 附件列表相关方法
    getDataListAttach() {
      this.selectedRowKeys = []
      this.loading = true
      this.$http
        .post('/Base_BasicData/Base_AttachmentsList/GetDataList', {
          PageIndex: this.paginationAttach.current,
          PageRows: this.paginationAttach.pageSize,
          SortField: 'Id',
          SortType: this.sorter.order, DeptId: this.DeptId,
          Search: { Condition: 'RelationId', Keyword: this.Id },
          ...this.filters
        })
        .then(resJson => {
          this.loading = false
          this.dataAttach = resJson.Data
          if (this.dataAttach) {
            const paginationAttach = { ...this.paginationAttach }
            paginationAttach.total = resJson.Total
            this.paginationAttach = paginationAttach
          }
        })
    },
    handleDeleteAttach(ids) {
      const thisObj = this
      // this.$confirm({
      //   title: '确认删除吗?',
      //   onOk() {
      //     return new Promise((resolve, reject) => {
      //       thisObj.$http.post('/Base_BasicData/Base_AttachmentsList/DeleteData', ids).then(resJson => {
      //         resolve()
      //         if (resJson.Success) {
      //           thisObj.$message.success('操作成功!')
      //           thisObj.getDataList()
      //         } else {
      //           thisObj.$message.error(resJson.Msg)
      //         }
      //       })
      //     })
      //   }
      // })
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        thisObj.$http
          .post('/Base_BasicData/Base_AttachmentsList/DeleteData', ids)
          .then(resJson => {
            // resolve()

            if (resJson.Success) {
              thisObj.$message.success('操作成功!')

              thisObj.getDataList()
            } else {
              thisObj.$message.error(resJson.Msg)
            }
          })
      })
    },
    handleAttachmentsTableChange(pagination) {
      this.paginationAttach = { ...pagination }
      this.getDataListAttach()
    }
  }
}
</script>
